package queries;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import values.User;

import exception.ServerDownException;

public class UserQueries 
{
	/**
	 * Sql sentence that gets the user's info given its login.
	 */
	private final static String SELECT_INFO_USER_GIVEN_LOGIN= "SELECT ALIAS, PHOTO FROM users WHERE LOGIN=?";
	
	/**
	 * Sql sentence that updates a user helpful counter.
	 */
	private final static String UPDATE_USER_HELPFUL_COUNTER="UPDATE users set HELPFUL_COUNTER=HELPFUL_COUNTER+1 WHERE LOGIN=?";
	
	/**
	 * 
	 */
	public User getUserInfo(String login, Connection session) throws ServerDownException
	{
		try
		{
			PreparedStatement ps = session.prepareStatement(SELECT_INFO_USER_GIVEN_LOGIN);
			ps.setString(1, login);
			ResultSet rs= ps.executeQuery();
			User u= null;
			if(rs.next())
			{
				u = new User(login, null, null, rs.getString("ALIAS"), rs.getString("PHOTO"));
			}
			return u;
		}
		catch(Exception e)
		{
			throw new ServerDownException(e.getLocalizedMessage());
		}	
	}
	
	public void updateUserHelpfulCounter(String login, Connection session) throws ServerDownException
	{
		try
		{
			PreparedStatement ps=session.prepareStatement(UPDATE_USER_HELPFUL_COUNTER);
			ps.setString(1,login);
			ps.executeUpdate();
		}
		catch(Exception e)
		{
			throw new ServerDownException(e.getLocalizedMessage());
		}
	}
}
